package com.baike.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class UDPClient {
    public static void main(String[] args) {

        udpClient();

    }

    public static void udpClient(){

        DatagramSocket datagramSocket = null;

        BufferedReader bufferedReader = null;

        String ip = "127.0.0.1";

        InetAddress inetAddress;

        try {
            inetAddress = InetAddress.getByName(ip);

            datagramSocket = new DatagramSocket();

            bufferedReader = new BufferedReader(new InputStreamReader(System.in,"UTF-8"));

            String sendString = null;

            while (true){
                sendString = bufferedReader.readLine().trim();

                byte[] sendBytes = sendString.getBytes(StandardCharsets.UTF_8);

                DatagramPacket datagramPacket = new DatagramPacket(sendBytes,sendBytes.length,inetAddress,10000);

                datagramSocket.send(datagramPacket);

                if("close".equals(sendString)){
                    break;
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(datagramSocket != null){
                datagramSocket.close();
            }
            if(bufferedReader != null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
